import React, { useState, useMemo } from "react";
// useMemo缓存的也是函数
// useMemo的语法和useCallback完全一样

// useMemo相当于vue的计算属性

/*
  useCallback和useMemo的区别
    1. useCallback缓存的函数本身
    2. useMemo缓存的是函数的返回值

    useCallback是可以转成useMemo的，加一层箭头函数
    useMemo不能转成useCallback
*/

const list = [1, 2, 3, 4, 5, 6, 7, 8, 9];

const App = () => {
  const [count, setCount] = useState(1);
  const total = useMemo(() => {
    console.log(123);
    let sum = 0;
    for (let i = 0; i < count * 100; i++) {
      sum += i;
    }
    return sum;
  }, [count]);

  const [name, setName] = useState("zhangsan");

  const oddList = useMemo(() => {
    return list.filter((item) => item % 2);
    // eslint-disable-next-line
  }, [list]);

  return (
    <>
      <h2>useMemo</h2>
      <p>count: {count}</p>
      <button onClick={() => setCount((v) => v + 1)}>btn</button>
      {/* <p>total: {total()}</p> */}
      <p>total: {total}</p>

      <p>name: {name}</p>
      <button onClick={() => setName("lisi")}>btn</button>

      <ul>
        {oddList.map((item) => (
          <li key={item}>{item}</li>
        ))}
      </ul>
    </>
  );
};

export default App;
